<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>规则名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="规则名称"
                    ></el-input>
                </div>
                <label>规则备注：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.remark"
                        clearable
                        placeholder="规则备注"
                    ></el-input>
                </div>

            </div>
            <div class="search-item">
                <label>所属学科：</label>
                <div class="table-query-input">
                    <category-select
                        :category-id.sync="queryData.categoryId"
                        :props="{}"
                    />
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                icon="el-icon-plus"
                style="margin-bottom: 2em"
                @click="addRule"
            >新增规则
            </el-button>
            <el-button
                type="danger"
                icon="el-icon-delete"
                style="margin-bottom: 2em"
                :disabled="ids.length === 0"
                @click="
                    tableDelete(
                        '/exam/rule/deleted-list',
                        {
                            ids: ids
                        },
                        true
                    )
                "
            >批量删除
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                border
                :data="tableData"
                style="width: 100%;min-height:40em"
                row-key="id"
                :highlight-current-row="true"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    type="selection"
                    min-width="55"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="规则名称"
                    width="150"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="totalScore"
                    label="规则总分"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="passScore"
                    label="规则及格分"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="remark"
                    label="规则备注"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建日期"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    label="最后操作者"
                    align="center"
                    :resizable="false"
                >
                    <template slot-scope="scope">
                        <div>
                            <p>{{ scope.row.finalModifyUserName }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="200"
                    align="center"
                    fixed="right"
                    :resizable="false"
                >
                    <template slot-scope="scope">
                        <el-button
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="editRule(scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="danger"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/exam/rule/deleted-list',
                                    {
                                        ids: [scope.row.id]
                                    },
                                    true
                                )
                            "
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            custom-class="two-dialog"
            width="800px !important"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRule">
                <el-input v-model="dataForm.id" type="hidden"></el-input>
                <div class="row">
                    <el-form-item label="规则名称" prop="name">
                        <el-input v-model="dataForm.name"></el-input>
                    </el-form-item>
                    <el-form-item
                        label="所属学科"
                        prop="categories">
                        <category-mult-select
                            :category-ids="categories"
                            :props="{multiple: true,emitPath:false,checkStrictly:true}"
                            @operate-category="operateCategory"
                        />
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="规则总分" prop="totalScore">
                        <el-input v-model.number="dataForm.totalScore"></el-input>
                    </el-form-item>
                    <el-form-item label="规则及格分" prop="passScore">
                        <el-input v-model.number="dataForm.passScore"></el-input>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="规则说明" prop="remark">
                        <el-input v-model="dataForm.remark" type="textarea" :rows="5"></el-input>
                    </el-form-item>
                </div>
            </el-form>
            <el-form
                ref="quNumForm"
                :model="quNumForm"
                label-width="8em"
                :rules="quNumFormRule">
                <div class="row">
                    <el-form-item label="单选题试题数" prop="singleNum">
                        <el-input v-model.number="quNumForm.singleNum"></el-input>
                    </el-form-item>
                    <el-form-item label="多选题试题数" prop="multipleNum">
                        <el-input v-model.number="quNumForm.multipleNum"></el-input>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="不定项试题数" prop="indefiniteMultipleNum">
                        <el-input v-model.number="quNumForm.indefiniteMultipleNum"></el-input>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="判断题试题数" prop="judgmentNum">
                        <el-input v-model.number="quNumForm.judgmentNum"></el-input>
                    </el-form-item>
                    <el-form-item label="填空题试题数" prop="fillNum">
                        <el-input v-model.number="quNumForm.fillNum"></el-input>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="问答题试题数" prop="questionNum">
                        <el-input v-model.number="quNumForm.questionNum"></el-input>
                    </el-form-item>
                    <el-form-item label="复合题试题数" prop="combinationNum">
                        <el-input v-model.number="quNumForm.combinationNum"></el-input>
                    </el-form-item>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="saveDataForm()"
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {TablePage} from "@/layout/mixin/iVue.js";
import CategorySelect from "@/components/CategorySelect";
import {post, put} from "@/api/request";
import CategoryMultSelect from "@/views/models/exam/component/CategoryMultSelect";

export default {
    name: "RuleIndex",
    components: {CategoryMultSelect, CategorySelect},
    mixins: [TablePage],
    data() {
        let checkNumber = (rule, value, callback) => {
            if (value === "") {
                return callback(new Error("不能为空"));
            }
            if (!Number.isInteger(value)) {
                callback(new Error("请输入数字值"));
            }
            if (value <= 0) {
                callback(new Error("请输入大于0的数字值"));
            } else if (value >= 1000000) {
                callback(new Error("数值过大"));
            } else {
                callback();
            }
        };
        let checkCategory = (rule, value, callback) => {
            if (value === undefined || value === "") {
                return callback(new Error("请至少选择一个学科"));
            } else {
                callback();
            }
        };
        let checkQuestionNum = (rule, value, callback) => {
            if (value === "") {
                return callback(new Error("不能为空"));
            }
            if (!Number.isInteger(value)) {
                callback(new Error("请输入数字值"));
            }
            if (value < 0) {
                callback(new Error("请输入大于或等于0的试题数"));
            } else if (value > 750) {
                callback(new Error("请输入小于100的试题数"));
            } else {
                callback();
            }
        };

        return {
            queryData: {
                name: "",
                remark: "",
                pageSize: 10,
                currentPage: 1,
            },
            tableData: [],
            ids: [],
            initAddForm: {
                id: null,
                viewName: null,
                remark: null,
                firstType: null
            },
            quNumForm: {
                singleNum: 0,
                multipleNum: 0,
                judgmentNum: 0,
                fillNum: 0,
                questionNum: 0,
                combinationNum: 0,
                indefiniteMultipleNum: 0
            },
            dataFormRule: {
                name: [
                    {required: true, message: "规则名称不可为空！", trigger: "blur"}
                ],
                categoryId: [
                    {required: true, message: "请选择一个学科", trigger: "change"}
                ],
                totalScore: [
                    {required: true, validator: checkNumber, trigger: "blur"}
                ],
                passScore: [
                    {required: true, validator: checkNumber, trigger: "blur"}
                ],
                categories: [
                    {required: true, validator: checkCategory, trigger: "blur"}
                ],
            },
            quNumFormRule: {},
            categories: []
        };
    },
    computed: {},
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        clearQuery() {
            (this.queryData = {}), this.search();
        },
        search(queryData) {
            this.loadTable("/exam/rule/page", queryData);
        },
        handleSelectionChange(val) {
            this.ids = [];
            const length = val.length;
            for (let n = 0; n < length; n++) {
                this.ids.push(val[n].id);
            }
        },
        filterAction(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        clickSelectAction(data, checked, indeterminate) {
            const actionCode = data.id;
            if (checked) {
                this.dataForm.actionCodes.push(actionCode);
            } else {
                this.dataForm.actionCodes.splice(
                    this.dataForm.actionCodes.indexOf(actionCode),
                    1
                );
            }
        },
        saveDataForm() {
            this.$refs.dataForm.validate((valid) => {
                if (valid) {
                    this.$refs.quNumForm.validate((validNum) => {
                        this.quNumForm.singleNum = (this.quNumForm.singleNum === null || this.quNumForm.singleNum === undefined) ? 0 : this.quNumForm.singleNum
                        this.quNumForm.multipleNum = (this.quNumForm.multipleNum === null || this.quNumForm.multipleNum === undefined) ? 0 : this.quNumForm.multipleNum
                        this.quNumForm.judgmentNum = (this.quNumForm.judgmentNum === null || this.quNumForm.judgmentNum === undefined) ? 0 : this.quNumForm.judgmentNum
                        this.quNumForm.fillNum = (this.quNumForm.fillNum === null || this.quNumForm.fillNum === undefined) ? 0 : this.quNumForm.fillNum
                        this.quNumForm.questionNum = (this.quNumForm.questionNum === null || this.quNumForm.questionNum === undefined) ? 0 : this.quNumForm.questionNum
                        this.quNumForm.combinationNum = (this.quNumForm.combinationNum === null || this.quNumForm.combinationNum === undefined) ? 0 : this.quNumForm.combinationNum
                        this.quNumForm.indefiniteMultipleNum = (this.quNumForm.indefiniteMultipleNum === null || this.quNumForm.indefiniteMultipleNum === undefined) ? 0 : this.quNumForm.indefiniteMultipleNum
                        if (validNum) {
                            this.dataForm.questionTotal =
                                this.quNumForm.singleNum +
                                this.quNumForm.multipleNum +
                                this.quNumForm.judgmentNum +
                                this.quNumForm.fillNum +
                                this.quNumForm.questionNum +
                                this.quNumForm.combinationNum+
                                this.quNumForm.indefiniteMultipleNum;
                            this.dataForm.content = [];
                            let ruleContent = {
                                siNum: this.quNumForm.singleNum,
                                muNum: this.quNumForm.multipleNum,
                                juNum: this.quNumForm.judgmentNum,
                                fiNum: this.quNumForm.fillNum,
                                quNum: this.quNumForm.questionNum,
                                comNum: this.quNumForm.combinationNum,
                                imNum: this.quNumForm.indefiniteMultipleNum
                            }
                            this.dataForm.content.push(ruleContent);
                            if (this.dataForm.id !== null) {
                                put("/exam/rule/update", this.dataForm).then(res => {
                                    if (res) {
                                        this.$message({
                                            message: "恭喜你，规则编辑成功",
                                            type: "success"
                                        });
                                        this.dialogFormVisible = false;
                                        this.search();
                                    }
                                })
                            } else {
                                post("/exam/rule/update", this.dataForm).then(res => {
                                    if (res) {
                                        this.$message({
                                            message: "恭喜你，规则添加成功",
                                            type: "success"
                                        });
                                        this.dialogFormVisible = false;
                                        this.search();
                                    }

                                })
                            }
                            this.quNumForm = {};
                        }
                    });
                }
            })
        },
        editRule(data) {
            this.dataForm = {};
            this.dialogFormTitle = "规则编辑";
            this.quNumForm = {};
            if (data.content !== null && data.content.length > 0) {
                data.content.map(v => {
                    this.$set(this.quNumForm, "singleNum", v.siNum);
                    this.$set(this.quNumForm, "multipleNum", v.muNum);
                    this.$set(this.quNumForm, "judgmentNum", v.juNum);
                    this.$set(this.quNumForm, "fillNum", v.fiNum);
                    this.$set(this.quNumForm, "questionNum", v.quNum);
                    this.$set(this.quNumForm, "combinationNum", v.comNum);
                    this.$set(this.quNumForm, "indefiniteMultipleNum", v.imNum);
                })
            }
            this.categories = [];
            let cateArray = [];
            if (data.categories !== null && data.categories.length > 0) {
                cateArray = data.categories.map(v => {
                    return v.id;
                })
            }
            this.categories = Object.assign([], cateArray);
            this.dataForm = data;
            this.dialogFormVisible = true;
        },
        addRule() {
            this.quNumForm = {};
            this.categories = [];
            this.clickAdd("添加规则")
        },
        operateCategory(vl) {
            if (vl.length > 0) {
                this.dataForm.categories = [];
                vl.map(id => {
                    let idData = {
                        id: id
                    }
                    this.dataForm.categories.push(idData)
                })
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.search-item {
    label {
        margin-left: 1em;
    }
}
</style>
